//
//  HMPlatform.swift
//  HealthMonitoring
//
//  Created by 珠海正杰 on 2018/9/7.
//  Copyright © 2018年 YTYanK. All rights reserved.
//
// 当前用户资料

import UIKit



typealias CommonVoidBlock = ()-> Void





/// 腾讯IM所有设置的初始化,配置以及业务逻辑入口，外部所的要使用IMSDK的地方，都间接能过HMPlatform调用
class HMPlatform: NSObject, TIMRefreshListener {

    let kEachKickErrorCode = 6208 //互踢下线错误码
    // 被踢下线时，如果当前在直播的时候，进行调用
    var offlineExitLivingBlock: CommonVoidBlock?
    
    /// 新消息block
    var newMessageBlock: ((Array<Any>)->())?
    // 会话列表
    var conversationList :[TIMConversation]?
    
    // 自动登录标记
    class func isAutoLogin() -> Bool {
        let num: NSNumber = UserDefaults.standard.object(forKey: "kHMPlatform_AutoLogin_Key") as! NSNumber
        return num.boolValue
    }
    
    class func setAutoLogin(autologin: Bool) {
        let kHMPlatform_AutoLogin_Key = "kHMPlatform_AutoLogin_Key"
        UserDefaults.standard.set(autologin, forKey: kHMPlatform_AutoLogin_Key)
    }
    
    
    
    /// 获取
    static let sharePlatform: HMPlatform = {
        let share = HMPlatform()
        return share
    }()

    
    /**
     *  初始化及配置imSDK
     *
     *  @param cfg 配置内容
     *
     *  @return 返回 HMPlatform 实例
     */
    class func configWith(cfg: Any) ->  HMPlatform {
        let _shared = HMPlatform.sharePlatform
        _shared.config(cfg: cfg)
        return _shared
    }
    /**
     *  初始化及配置imSDK
     *
     *  @param cfg 配置内容
     */
    func config(cfg: Any)  {
        
        let manager: TIMManager = TIMManager.sharedInstance()
//        manager.setEnv(1) // 环境 - 0 正式
        manager.setMessageListener(HMPlatform.sharePlatform)
        manager.setConnListener(HMPlatform.sharePlatform) //网络事件通知
        manager.setUserStatusListener(HMPlatform.sharePlatform) //用户状态变更
//        manager.setLogListener(HMPlatform.sharePlatform)  //日志
        manager.initSdk(HMLoginParam.share.kSdkAppId)//sdk id
    }
    
 
    
    func onLogoutCompletion() {
        offlineLogin()
    }
    
    
    /// 被踢下线，则清空单例中的数据，再登录后再重新创建
    func offlineLogin() {
//        let manager = TIMManager.sharedInstance()
//        manager?.remove()
    }
    /**
     *  退出登录
     *
     *  @param succ 登录信息
     *  @param fail 失败
     *
     */
    func logout(succ: @escaping TIMLoginSucc, fail: @escaping TIMFail) {
      //  weak let ws: HMPlatform = self
        TIMManager.sharedInstance().logout({
//            ws.onlo
             succ()
        }) { (code, err) in
            if fail != nil {
                fail(code, err)
            }
        }
        
    }
    
}


//MARK: 回调   可以直接使用 -setMessageListener:
extension HMPlatform: TIMMessageListener {
    /// 新消息回调---新消息都会来这里
    func onNewMessage(_ msgs: [Any]!) {
         print("HMPlatform---> 有新消息来了", msgs)
        if HMPlatform.sharePlatform.newMessageBlock != nil {
            HMPlatform.sharePlatform.newMessageBlock!(msgs)
        }
       
    }
}

//MARK: 网络事件通知
extension HMPlatform: TIMConnListener {
    func onConnSucc() {
        print("腾讯IM 连接成功")
    }
    func onConnFailed(_ code: Int32, err: String!) {
        print("腾讯IM---->\(code)-->\(err)")
    }
    
    func onDisconnect(_ code: Int32, err: String!) {
        print("\(code)")
    }

    /// 连接中
    func onConnecting() {
         print("HMP---->>onConnecting")
    }
    /// 断线重连失败
    func onReConnFailed(_ code: Int32, err: String!) {
        print("HMP---->onReConnFailed")
    }
    /// 刷新会话
    func onRefresh() {
         print("HMP--->onRefresh")
    }

    
 
}

//MARK: 户在线状态通知
extension HMPlatform: TIMUserStatusListener {
    /// 被T t通知
    func onForceOffline() {
        print("onForceOffline")
        
        HMPlatform.getLoginSig()
        
    }
    
    /// 用户登录的 userSig 过期（用户需要重新获取 userSig 后登录）
    func onUserSigExpired() {
        print("onUserSigExpired")
    }
}

//MARK: 腾讯 IM 日志
extension HMPlatform: TIMLogListener {
    func log(_ lvl: TIMLogLevel, content: String!) {
        print("----->腾讯IM 日志：", content)
    }
}


//MARK: 腾讯 IM 登陆
extension HMPlatform {
    /**
     *  登录IMSDK
     * @param  param 登录信息
     * @apram  succ  成功回调
     * @apram  fail  失败回调
     */
    func loginIMSDK(param: TIMLoginParam, succ: @escaping TIMLoginSucc, fail: @escaping TIMFail) {
        //       MBProgressHUD
        TIMManager.sharedInstance().login(param, succ: {
            debugPrint("登录成功:\(param.identifier) tinyid:\(IMSdkInt.sharedInstance().getTinyId()) sig:\(param.userSig)")
               succ()
            
            
            
            
        }) { (hm_code, hm_msg) in
            debugPrint("TIMLogin 失败: code=\(hm_code ) err=\(hm_msg as! String)")
            if hm_code == self.kEachKickErrorCode {
                
                print("---------->>>: 账号被登陆，互T？\(hm_code)")
                //互踢重联，重新再登录一次
//                HMLoginParam.wipeData()
            
                let app =  UIApplication.shared.delegate as! AppDelegate
                let optionMenu = UIAlertController.init(title: "当前用户已被登陆，请重新登录!", message: nil, preferredStyle: .alert)
                let cancelAction = UIAlertAction(title: "知道了", style: UIAlertActionStyle.cancel, handler:{ (alert) in
//                    print("取消")

                    UIView.transition(with: app.window!, duration: 0.6, options: UIViewAnimationOptions.transitionFlipFromLeft, animations: {
                        let oldState = UIView.areAnimationsEnabled
                        UIView.setAnimationsEnabled(false)
                        app.switchLogin(showLogin: nil)
                        UIView.setAnimationsEnabled(oldState)
                    })
                })
            
                optionMenu.addAction(cancelAction)
                
                app.window?.rootViewController?.present(optionMenu, animated: true, completion: nil)
        
            }else {
               fail(hm_code, hm_msg)
            }
        }
        
    }
    /**
     *  登出IMSDK
     * @apram  succ  成功回调
     * @apram  fail  失败回调
     */
    func logoutIMSDK(succ: @escaping TIMLoginSucc) {
        TIMManager.sharedInstance()?.logout({
            print("退出成功！")
            succ()
        }, fail: { (hm_code, hm_msg) in
            print("------->>>",hm_msg)
        })
    }

    /**
       通过后台服务器 获取 腾讯 IM sig码, 第一次登陆后要获取
     */
    class func getLoginSig() {
        
        // 判断是否登陆过
        if  NetRequestTool.shareInstance.token.count > 0 {
            
            // 判断是否拥有 sig
            let sigStr  = UserDefaults.standard.string(forKey: "hm_sig")
            if (sigStr == "" || sigStr == nil) {
                NetRequestTool.shareInstance.met = .get
                NetRequestTool.request(url: "user/tx-im/signature", parameters: [:], success: { (json) in
                    if json["data"]["sig"].stringValue.count > 0 {
                        
                        let sig = json["data"]["sig"].stringValue
                        UserDefaults.standard.set(sig, forKey: "hm_sig") // 保存验证码
                        
                        let userID: Dictionary<String, Any> = HMLoginParam.share.user
                        // 获取之后直接 IM 登陆
                        let param = TIMLoginParam()
                        param.accountType = "25177"
                        param.appidAt3rd = String(HMLoginParam.share.kSdkAppId)
                        param.sdkAppId = HMLoginParam.share.kSdkAppId
                        param.identifier = (userID["id"] as! String)
                        param.userSig = sig
                        HMPlatform.sharePlatform.loginIMSDK(param: param, succ: {
                            print("登录成功")
                        }) { (code, err) in
                            print("261-YTY----->> IM登陆失败:\(code)\(err)")
                        }
                    }else {
                        // 如果没有请循环调哦
                    }
                    
                }, fail: { (code, msg) in
                    print("获取sig 失败")
                }) { }
            }else {
                // 如果不是空
                let userID: Dictionary<String, Any> = HMLoginParam.share.user
                // 获取之后直接 IM 登陆
                let param = TIMLoginParam()
                param.accountType = "25177"
                param.appidAt3rd = String(HMLoginParam.share.kSdkAppId)
                param.sdkAppId = HMLoginParam.share.kSdkAppId
                param.identifier = (userID["id"] as! String)
                let sigStr = UserDefaults.standard.string(forKey: "hm_sig")
                param.userSig = sigStr
                HMPlatform.sharePlatform.loginIMSDK(param: param, succ: {
//                    print("----->>IM登陆成功")
                }) { (code, msg) in
                    print("288-YTY----->> IM登陆失败:\(code)")
                }
                
                
                
            }
       
        }
    }
    
    /**
     获取与某个人的会话  -- C2C
     */
   class func getSomeoneConversation(_ id: String) -> TIMConversation {
        
        let con: TIMConversation = (TIMManager.sharedInstance()?.getConversation(.C2C, receiver: id))!
        return con
    }
    
    /**
       获取当前登陆用户
     */
    class func getCurrentUserId() -> String {
        var _user = ""
        if TIMManager.sharedInstance()?.getLoginUser() != nil {
           _user = (TIMManager.sharedInstance()?.getLoginUser())!
        }
        return _user
    }
    
    
//    class func getFriend () {
//    
//      TIMFriendshipManager.sharedInstance()?.getUsersProfile(<#T##users: [Any]!##[Any]!#>, succ: <#T##TIMFriendSucc!##TIMFriendSucc!##([Any]?) -> Void#>, fail: <#T##TIMFail!##TIMFail!##(Int32, String?) -> Void#>)    //getUsersProfile(<#T##TIMFriendshipManager#>)
//    }
    
    
    /**
     获取会话列表
     */
    class func getConversationList(ary:(Array<Any>)->()) {
        var newList = Array<Any>()
        
        // 这里会包含各种会话
        let list =  (TIMManager.sharedInstance()?.getConversationList())!
        
        // 筛选
        for msg in list {
            let con = msg as! TIMConversation
            let str =  HMPlatform.getCurrentUserId()
            if  con.getReceiver() != "" &&  con.getReceiver() != str  {
                newList.append(msg)
            }else {
                print("no=====>",con)
            }
        }
        
        ary(newList)
    }
    
    /**
     获取全部好友
     */
    class func getAllFriendList(_ ary: ([Any])->()) {
        TIMFriendshipManager.sharedInstance()?.getFriendList({ (ary) in
            let profile = ary as! TIMUserProfile
        }, fail: { (code, err) in
            print("-----")
        })
    }
    
    
    /**
     会话列表获取
     */
    func setConversationList() {
        //话类型，如果是单聊，填写 TIM_C2C，如果是群聊，填写TIM_GROUP
        // 会话标识，单聊情况下，receiver为对方帐号identifier, 群聊情况下，receiver为群组Id
        
//        let dic = HMLoginParam.share.user
//        let id = (dic["id"] as! String)
        
      //  let id: String = (TIMManager.sharedInstance()?.getLoginUser())!
//
//
//        let sess: TIMConversation = (TIMManager.sharedInstance()?.getConversation(TIMConversationType.C2C, receiver: id))!
//
//        sess.getMessage(2, last: nil, succ: { ( msgs:[Any]?) in
//            print("------>>获取信息成功")
//        }) { ( code:Int32, msg:String?) in
//            print("---------->>>获取失败")
//        }
        
//        let con:TIMConversation = TIMManager.sharedInstance()?.getConversation(TIMConversationType.C2C, receiver: "T##String!")
//        
//        TIMFriendshipManager.sharedInstance()?.getSelfProfile({ (profile) in
//           print("-------->>>",profile)
//        }, fail: { (code, err) in
//            print("获取自己信息失败。\(code)")
//        })
        
        //
        let list =  (TIMManager.sharedInstance()?.getConversationList())!
   /*
        if list.count > 0 {
            for (v) in list {
                print("----->>", v)
                
                let hmp_conversation: TIMConversation =  v as! TIMConversation
                conversationList?.append(hmp_conversation)
                
                // 获取会话人，单聊为对方账号，群聊为群组Id // 聊天对方的id
                let strReceiver =  hmp_conversation.getReceiver()
                //获取会话所属用户的id, 自己的id
                let strId = hmp_conversation.getSelfIdentifier()
                
                let arys = hmp_conversation.getLastMsgs(20)
                
                hmp_conversation.getMessage(10, last: nil, succ: { (msgs:[Any]?) in
                    print("------>>获取信息成功", msgs)
                }) { ( code:Int32, msg:String?) in
                    print("---------->>>获取失败")
                }
            }
        }
       */
        
        
    }
    /**
     IM 获取当前登陆用户
     */
//     func 
    
    
//    class func
}





